package cn.sc.allinpay.allfavour.business.main;

import static cn.sc.allinpay.allfavour.app.App.getContext;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.usdk.core.data.ResponseData;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.App;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.business.cashier.CashierActivity;
import cn.sc.allinpay.allfavour.business.common.app.Global;
import cn.sc.allinpay.allfavour.business.common.data.CashierData;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.OrderPaymentInfo;
import cn.sc.allinpay.allfavour.business.common.data.PayInfo;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.PosInfo;
import cn.sc.allinpay.allfavour.business.common.data.SpOrderInfo;
import cn.sc.allinpay.allfavour.business.common.data.SpToken;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;
import cn.sc.allinpay.allfavour.business.common.utils.SpUtils;
import cn.sc.allinpay.allfavour.business.login.LoginActivity;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;

/**
 * 主界面 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class MainPresenter extends PaiPresenter<MainContract.View> implements MainContract.Presenter {
    public static final int REQ_CHECK = 0x01;
    private PosData posData;//Pos对象
    private OrderData order;
    private TransRecord transRecord;//交易记录，部分抵扣成功和交易详情进入时


    private MainModel model = new MainModel();
    private BroadcastReceiver mainReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.Action.ACTION_CASHIER_LOGIN_OUT.equals(action)) {//收银员退出登录
                relogin();
            }
        }
    };

    @Override
    protected Intervenor createIntervenor() {

        return new Intervenor() {
            @Override
            public void onResume() {
                super.onResume();

                model.spServer(new MpCallBack<String, String>() {
                    @Override
                    public void onSuccess(String serverName) {

                        Global global = Global.getInstance();
                        String localServer = global.getServer();
                        String tips = "";

                        if (serverName.equals("backup") && !localServer.equals(serverName)) {
                            if (model.getGlobal().getPayInfo() != null) {
                                return;
                            }
                            tips = "因系统调整，进入“极速收银”模式，营销功能暂时不可用，程序员小哥哥正在快马加鞭处理";
                            showChannelTips(serverName, tips);
                        }

                        if (!serverName.equals("backup") && localServer.equals("backup")) {
                            tips = "系统调整完毕，重新登陆后可正常使用";
                            showChannelTips(serverName, tips);
                        }
                    }

                    @Override
                    public void onFailure(String resp, String message) {

                    }
                });
            }

            @Override
            public void onStop() {
                super.onStop();
            }

            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (data != null && data.getExtras() != null) {
                    Bundle extras = data.getExtras();
                    ResponseData result = (ResponseData) extras.getSerializable("RESPONSE");
                    if (result != null) {
                        try {
                            if (result.getValue("REJCODE").equals("00")) {
                                PayInfo payInfo = model.getGlobal().getPayInfo();

                                String orderJSON = payInfo.getOrderJSON();
                                String transRecordJSON = payInfo.getTransRecordJSON();
                                String posDataJson = payInfo.getPosDataJSON();
                                if (!TextUtils.isEmpty(orderJSON)) {
                                    order = JSON.parseObject(orderJSON, OrderData.class);
                                }
                                if (!TextUtils.isEmpty(transRecordJSON)) {
                                    transRecord = JSON.parseObject(transRecordJSON, TransRecord.class);
                                }
                                if (!TextUtils.isEmpty(posDataJson)) {
                                    posData = JSON.parseObject(posDataJson, PosData.class);
                                } else {
                                    posData = new PosData();
                                }
                                posData.setTerminalId(result.getValue("TER_ID"));//终端号
                                posData.setMerchantId(result.getValue("MERCH_ID"));//商户id
                                posData.setMerchantName(result.getValue("MERCH_NAME"));//商户名称
                                if (requestCode == REQ_CHECK) {
                                    if (payInfo.getType().equals("pay")) {
                                        if (result.getValue("BUSINESS_ID").equals("100100001")) {
                                            posData.setTransType("消费");//交易类型
                                            posData.setTraceNo(result.getValue("TRACE_NO"));//凭证号
                                            posData.setBatchNo(result.getValue("BATCH_NO"));//批次号
                                            posData.setReferenceNo(result.getValue("REF_NO"));//参考号
                                            String dateTime = AllinUtils.getSysYear() + result.getValue("DATE") + result.getValue("TIME");
                                            posData.setDateTime(dateTime);//交易时间 格式yyyyMMddHHmmss
                                            posData.setCardNo(result.getValue("CARDNO"));//卡号
                                            posData.setIssue(result.getValue("ISS_NO"));//发卡行
                                            posData.setTransactionNumber(result.getValue("TRANS_TICKET_NO"));//交易单号
                                            if (transRecord != null) {
                                                //支付成功
                                                updRecord(2);
                                            } else {
                                                //无抵扣，支付成功，
                                                saveRecord(order.getOrderId(), 2, 0);
                                            }
                                            Date myDate1 = new Date();
                                            DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
                                            try {
                                                myDate1 = dateFormat1.parse(dateTime);
                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                            }
                                            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            view.loading();
                                            model.payNotify(payInfo.getOrderId(), "bank", "PAY", dateFormat2.format(myDate1), AmtUtils.changeY2F(posData.getCashAmt()), AmtUtils.changeY2F(posData.getAmount()), posData.getTransactionNumber(), new MpCallBack<JSONObject, String>() {
                                                @Override
                                                public void onSuccess(JSONObject resp) {
                                                    model.getGlobal().setPayInfo(null);
                                                    SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, "");
                                                    view.loaded();
                                                    view.toast("校正成功");
                                                    model.getGlobal().setPayInfo(null);
                                                    SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                                                }

                                                @Override
                                                public void onFailure(String resp, String message) {
                                                    view.loaded();
                                                    view.prompt(message);
                                                }
                                            });
                                        }
                                    }

                                    if (payInfo.getType().equals("cancel")) {
                                        if (result.getValue("BUSINESS_ID").equals("200100001")) {
                                            posData.setTraceNo(result.getValue("TRACE_NO"));//凭证号
                                            posData.setBatchNo(result.getValue("BATCH_NO"));//批次号
                                            posData.setReferenceNo(result.getValue("REF_NO"));//参考号
                                            String dateTime = AllinUtils.getSysYear() + result.getValue("DATE") + result.getValue("TIME");
                                            posData.setDateTime(dateTime);//交易时间 格式yyyyMMddHHmmss
                                            posData.setTransactionNumber(result.getValue("TRANS_TICKET_NO"));//交易单号
                                            transRecord.setState(4);//撤销成功
                                            DbDao<TransRecord> dbDao = model.getDao(TransRecord.class);
                                            dbDao.update(transRecord);

                                            Date myDate1 = new Date();
                                            DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                            view.loading();
                                            model.payNotify(transRecord.getOrderId(), "bank", "CANCEL", dateFormat2.format(myDate1), "0", "0", posData.getTransactionNumber(), new MpCallBack<JSONObject, String>() {
                                                @Override
                                                public void onSuccess(JSONObject resp) {
                                                    view.loaded();
                                                    view.toast("校正成功");
                                                    model.getGlobal().setPayInfo(null);
                                                    SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                                                }
                                                @Override
                                                public void onFailure(String resp, String message) {
                                                    view.loaded();
                                                    view.prompt(message);
                                                }
                                            });
                                        }
                                    }
                                }
                            } else {
                                view.loaded();
                                String error = result.getValue("REJCODE_CN");
                                view.toast(error);

                                if (result.getValue("REJCODE").equals("X3")) {
                                    model.getGlobal().setPayInfo(null);
                                    SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                                }
                            }
                        } catch (Throwable t) {
                            view.loaded();
                            Log.e("uDemo", "Could not parse malformed JSON: \"" + result + "\"");
                        }
                    } else {
                        view.loaded();

                    }
                } else {
                    view.loaded();
                }
            }
        };
    }

    private void showChannelTips(String serverName, String tips) {
        Global global = Global.getInstance();
        global.setServer(serverName);
        SpUtils.put(view.getContext(),Constant.SPNAME, Constant.SpKey.SERVER_NAME, serverName);

        view.prompt(false, tips, new OnPromptListener("确定", "取消") {
            @Override
            public void onPositive(DialogInterface dialog, int which) {
                dialog.dismiss();
                App.getContext().sendBroadcast(new Intent(Constant.Action.ACTION_CASHIER_LOGIN_OUT));
            }

            @Override
            public void onNegative(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
    }

    private void relogin() {
        DeviceLogin.logout();//退出主控
        model.getGlobal().setCashierData(null);
        model.getGlobal().setToken(null);
        model.getGlobal().setUserInfo(null);
        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.CashierData, "");
        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.Token, "");
        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.UserIfo, "");
        view.toActivity(LoginActivity.class, null);
        view.finish();
    }

    /**
     * 保存交易记录
     *
     * @param orderId   订单id
     * @param state     支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @param sellState 抵扣状态  0:无抵扣(普通交易) 1:抵扣成功  2:抵扣撤销 3:全额抵扣成功
     * @return
     */
    private int saveRecord(String orderId, int state, int sellState) {
        TransRecord record = new TransRecord();
        record.setTransNo(orderId);//订单id
        record.setOrderId(orderId);//订单id
        record.setTransAmt(order.getTransAmt());//总交易金
        record.setPaidAmt(order.getPaidAmt());//实际支付金额
        record.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString() : null);//会员优惠金额
        record.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        record.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额
        record.setTransDate(posData.getDateTime().substring(0, 8));//交易日期
        record.setTransTime(posData.getDateTime().substring(8));//交易时间
        record.setState(state);
        record.setSellState(sellState);//销账成功
        record.setOrderData(JSON.toJSONString(order));
        record.setPosData(JSON.toJSONString(posData));
        return model.saveTransRecord(record);
    }

    /**
     * 修改交易记录
     *
     * @param state 支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @return
     */
    private int updRecord(int state) {
        transRecord.setState(state);
        transRecord.setPosData(JSON.toJSONString(posData));
        return model.updTransRecord(transRecord);
    }

    @Override
    public void start() {

        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.Action.ACTION_CASHIER_LOGIN_OUT);
        view.registerReceiver(mainReceiver, filter);

        view.loading("数据处理中...");
        model.deleteCheckRecord(new MpCallBack<Integer, String>() {
            @Override
            public void onSuccess(Integer resp) {
                view.loaded();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.toast(message);
            }
        });
        CashierData cashierData = model.getGlobal().getCashierData();

        if (cashierData != null) {
            view.showStore(cashierData.getStoreName());
            view.showOperatorNo(cashierData.getCashierNo());
            view.showOperator(cashierData.getCashierName());
        }
    }


    @Override
    public boolean isPosInfoExist() {
        PosInfo posInfo = model.getGlobal().getPosInfo();
        return posInfo != null;
    }

    @Override
    public void checkOrder(View view1) {
        if (model.getGlobal().getPayInfo() != null) {
            view.loading("订单校正中, 请稍后");
            AllinUtils.orderInfoByTransCheck(view.getActivity(), model.getGlobal().getPayInfo().getOrderId(), REQ_CHECK);
        } else {
            view.showPay(view1);
        }
    }

    @Override
    public void startCashierActivity(String amt) {
        if (TextUtils.isEmpty(amt)) {
            view.prompt("交易金额不能为空");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(Constant.BundleKey.TRANS_AMT, amt);
        view.toActivity(CashierActivity.class, bundle);
    }
}
